package vip.ifmm.lehouse.api.gateway.config;

import com.alibaba.dubbo.config.annotation.Reference;

import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import vip.ifmm.lehouse.api.gateway.annotation.FromSession;
import vip.ifmm.lehouse.api.gateway.utils.CookieUtil;
import vip.ifmm.lehouse.common.bo.SessionBo;
import vip.ifmm.lehouse.common.dto.ServerResponse;
import vip.ifmm.lehouse.user.service.api.UserLoginService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 参数解析器
 *
 * @author Red
 * email: 1318944013@qq.com
 * date: 2019/6/16 20:21
 */
@Service
public class UserArgumentResolver implements HandlerMethodArgumentResolver {

	// 远程调用用户登录服务
	@Reference(owner = "red")
	private UserLoginService userLoginService = null;

	// 参数满足条件才进行解析
	public boolean supportsParameter(MethodParameter parameter) {
		Class<?> clazz = parameter.getParameterType();
		// 必须是SessionBo类且标注了FromSession注解
		return clazz == SessionBo.class && parameter.getParameterAnnotation(FromSession.class) != null;
	}

	// 对满足条件的参数进行解析
	public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory)  {
		// 拿到request 和 response
		HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
		HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);

		// 防止没有cookie 尝试拿参数
		String paramToken = request.getParameter(CookieUtil.COOKIE_KEY);
		// 从cookie中取出token
		String cookieToken = CookieUtil.getCookieValue(request, CookieUtil.COOKIE_KEY);
		// 如果cookie和参数中的token都为空，返回null
		if(StringUtils.isEmpty(cookieToken) && StringUtils.isEmpty(paramToken)) {
			return null;
		}
		String token = StringUtils.isEmpty(cookieToken) ? paramToken : cookieToken;
		// 延长cookie时间
		// CookieUtil.addCookie(response, token);
		// 拿到redis中的session key为token
		ServerResponse<SessionBo> sessionResult = userLoginService.getSessionByToken(token);
		if(sessionResult.isSuccess()) {
			return sessionResult.getData();
		} else {
			return null;
		}
	}


}
